﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Web;
using System.IO;
using TheMovieDBV3;

namespace MOJsdk
{
    public class InternetInfo
    {
        private string _apiKey;

        public InternetInfo(string TmdbApiKey)
        {
            _apiKey = TmdbApiKey;

            onSearchMovieCompleted += delegate { };
            onError += delegate { };
        }

        public void SearchMovieAsync(string query)
        {
            AsyncQueryHandler th = new AsyncQueryHandler(searchmovieasync);
            th.BeginInvoke(query, null, null);
        }
        public List<MojWebMovie> SearchMovie(string query)
        {
            try
            {
                List<TmdbMovie> _list = TmdbMovie.SearchMovie(query, _apiKey);

                List<MojWebMovie> results = new List<MojWebMovie>();
                foreach (var v in _list)
                    results.Add(new MojWebMovie(v));

                return results;
            }
            catch (Exception ex)
            {
                onError(new ErrorReporter()
                {
                    ErrorCode = "DownMovieInfoData",
                    ErrorDetails = ex.ToString(),
                    ErrorMessage = "Error downloading movie data",
                });

                return new List<MojWebMovie>();
            }
        }
        private void searchmovieasync(string query)
        {
            try
            {
                List<TmdbMovie> _list = TmdbMovie.SearchMovie(query, _apiKey);

                List<MojWebMovie> results = new List<MojWebMovie>();
                foreach (var v in _list)
                    results.Add(new MojWebMovie(v));

                onSearchMovieCompleted(results);
            }
            catch (Exception ex)
            {
                onError(new ErrorReporter()
                {
                    ErrorCode = "DownMovieInfoData",
                    ErrorDetails = ex.ToString(),
                    ErrorMessage = "Error downloading movie data",
                });
            }
        }

        private delegate void AsyncQueryHandler(string query);

        public delegate void SearchMovieHandler(List<MojWebMovie> Results);
        public delegate void ErrorReporterHandler(ErrorReporter Error);
        public event SearchMovieHandler onSearchMovieCompleted;
        public event ErrorReporterHandler onError;

        public static string API_KEY
        { get { return "6b3254ee1455766f9901e9ec383670d8"; } }
    }

    public class MojWebMovie
    {
        private List<MojWebImage> _posters;
        private List<MojWebImage> _back;
        private MojWebImage _mainImage;

        public MojWebMovie(TmdbMovie data)
        {
            _posters = new List<MojWebImage>();
            foreach (var v in data.Posters)
                _posters.Add(new MojWebImage(v));

            _back = new List<MojWebImage>();
            foreach (var v in data.Backdrops)
                _back.Add(new MojWebImage(v));

            if (data.MainPoster != null)
            {
                _mainImage = new MojWebImage(data.MainPoster);
            }
            else
            {
                _mainImage = null;
            }

            Title = data.Title;
            OriginalTitle = data.OriginalTitle;

            Year = data.ReleaseYear;
            MovieId = data.MovieId;
            Imdb_Id = data.Imdb_Id;
            Genres = data.Genres;
            Cast = data.Cast;
            Director = data.Director;
            Writer = data.Writer;
            Tagline = data.Tagline;
        }

        public string Title { get; set; }
        public string OriginalTitle { get; set; }

        public string Year { get; set; }
        public string MovieId { get; set; }
        public string Imdb_Id { get; set; }
        public string Tagline { get; set; }
        public List<string> Genres { get; set; }
        public List<string> Cast { get; set; }
        public List<string> Director { get; set; }
        public List<string> Writer { get; set; }

        public List<MojWebImage> Posters
        { get { return _posters; } }
        public List<MojWebImage> Backdrops
        { get { return _back; } }
        public MojWebImage Cover
        { get { return _mainImage; } }
    }
    public class MojWebImage
    {
        private IHost _host;

        private string _ThumbPath, _OriginalPath, _ThumbUrl, _OriginalUrl;

        public MojWebImage(TmdbImage data)
        {
            _host = MojHost.GetHost;
            Type = data.TYPE;

            _ThumbUrl = data.ThumbPath;
            _ThumbPath = Path.Combine(MojFoldersEnum.TemporaryFolder.Value(), data.Name);
            _OriginalUrl = data.OriginalPath;
            _OriginalPath = Path.Combine(MojFoldersEnum.TemporaryFolder.Value(), "Origin" + data.Name);
        }
        public MojWebImage()
        {

        }

        public TmdbImageType Type { get; set; }
        public string ThumbUrl { get { return _ThumbUrl; } }
        public string OriginalUrl { get { return _OriginalUrl; } }
        public string ThumbPath { get { return _ThumbPath; } }
        public string OriginalPath { get { return _OriginalPath; } }
        public bool IsAvaible 
        { 
            get 
            {
                if (File.Exists(_ThumbPath) && File.Exists(_OriginalPath))
                    return true;

                return false;
            } 
        }

        public bool DownloadThumbPath()
        {
            try
            {
                WebClient c = new WebClient();

                if (!File.Exists(_ThumbPath))
                    c.DownloadFile(_ThumbUrl, _ThumbPath);

                return true;
            }
            catch (Exception ex)
            {
                _host.ReportError(new ErrorReporter()
                {
                    ErrorCode = "TMDBIMGxDOWN",
                    ErrorDetails = ex.ToString(),
                    ErrorMessage = "Error downloading an image",
                });

                return false;
            }
        }
        public bool DownloadOriginalFile()
        {
            try
            {
                WebClient c = new WebClient();

                if (!File.Exists(_OriginalPath))
                    c.DownloadFile(_OriginalUrl, _OriginalPath);

                return true;
            }
            catch (Exception ex)
            {
                _host.ReportError(new ErrorReporter()
                {
                    ErrorCode = "TMDBIMGxORIGxDOWN",
                    ErrorDetails = ex.ToString(),
                    ErrorMessage = "Error downloading an image",
                });

                return false;
            }
        }

        #region Static
        public static MojWebImage CreateNoPosterImage()
        {
            MojWebImage w = new MojWebImage();

            w._host = MojHost.GetHost;
            w._OriginalPath = MojEnviromentVarsEnum.DefaultCoverPath.Value();
            w._ThumbPath = MojEnviromentVarsEnum.DefaultCoverPath.Value();

            w.Type = TmdbImageType.Poster;

            return w;
        }
        #endregion
    }
}